package com.example.library_demo.service.impl;

import com.example.library_demo.common.Result;
import com.example.library_demo.dto.recharge.RechargeDTO;
import com.example.library_demo.entity.Card;
import com.example.library_demo.entity.Recharge;
import com.example.library_demo.exception.BizException;
import com.example.library_demo.mapper.RechargeMapper;
import com.example.library_demo.service.ICardService;
import com.example.library_demo.service.IRechargeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Eric
 * @since 2024-11-28
 */
@Service
public class RechargeServiceImpl extends ServiceImpl<RechargeMapper, Recharge> implements IRechargeService {
    @Autowired
    private ICardService cardService;

    @Override
    @Transactional
    public Boolean topUp(RechargeDTO rechargeDTO,Long userId) {
        Card card = cardService.getById(rechargeDTO.getCardId());
        if (null == card) {
            throw new BizException("Card is not exist.");
        }
        Recharge recharge = new Recharge();
        BeanUtils.copyProperties(rechargeDTO,recharge);
        recharge.setUserId(userId);
        if(save(recharge)){
            BigDecimal topUpMoney = new BigDecimal(rechargeDTO.getTopUpMoney().toPlainString());
            card.setBalance(card.getBalance().add(topUpMoney));
            cardService.updateById(card);
            return true;
        } else {
            return false;
        }
    }
}
